import request from '@/utils/request'
import router from '@/router'
import Layout from '@/layout'
import {loadPage} from './loadPage'
// 获取路由
export const getRouters = () => {
  return request({
//    url: process.env.VUE_APP_LOGIN_API+'/VUELogin/Menu',
    url: process.env.VUE_APP_LOGIN_API+'/getRouters',
    method: 'get'
  })
}
export const routepathList=[];
export const errorMessage={};
export function gotoPage(page) {
 var params=page.split("?");
 page=params[0];

//router.addRoutes(accessRoutes)
//	console.log(router.resolve(page));
//	console.log(routepathList);
	if (routepathList.indexOf(page)==-1){
	  const accessRoutes =  
//		  {
//		name: page,
//		path: page,
//		component: (resolve) => require(["@/views"+page], resolve),
////		hidden: true,
//	  };
	  {
		name: page,
		path: page+"/menu",
		component: Layout,
		hidden: true,
		children: [
		  {
			path: page,
			component: (resolve) =>loadPage(page,resolve)
		  }
		]
	  };
	  router.addRoutes([accessRoutes]);
	  routepathList.push(page);
	}
	if (params.length>1){
		router.push(page+"?"+params[1]);
	}else{
		router.push(page);
	}
	return page;
}

export function loadTreeTable(asyncRouterMap,key,pkey) {
	return filterTree(asyncRouterMap,key,pkey).slice(0,1)
}

export function getChildren(list,id,pkey){
	const arr=[];
//	for(let [k,v] of list) {  
	for (var k in list){
		var v=list[k];
		if (v[pkey]==id){
			arr.push(v);
		}
	}
//    }
	return arr;
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterTree(asyncRouterMap,key,pkey) {
//	for(let [index,route] of asyncRouterMap) { 
	for (var index in asyncRouterMap){
	const route=asyncRouterMap[index]
	const children=getChildren(asyncRouterMap,route[key],pkey);
	
	if (children.length>0){
		route.children = filterTree(children,key,pkey)
	}

    }
    return asyncRouterMap
//  })
}
